from concurrent.futures import ThreadPoolExecutor,as_completed,wait
import time

def get_html(times):
    time.sleep(times)
    print(f"get page {times} success")
    return times

urls = [2,6,3,7]

def main_batch():
    executor = ThreadPoolExecutor(max_workers=2)
    tasks = [executor.submit(get_html, (url)) for url in urls]
    # as_completed 生成器,无序返回，哪个任务先结束就先返回哪个
    for t in as_completed(tasks):
        #print(t.done())
        print(t.result())

def main_batch2():
    executor = ThreadPoolExecutor(max_workers=2)
    #map 方式可以 按照 任务的次序返回结果
    for result in executor.map(get_html,urls):
        print(result)

def main_batch_wait():
    executor = ThreadPoolExecutor(max_workers=2)
    tasks = [executor.submit(get_html, (url)) for url in urls]
    #可以等待所有任务执行完毕,阻塞
    wait(tasks)
    print("OVER")

def main():
    executor = ThreadPoolExecutor(max_workers=2)
    future1 = executor.submit(get_html,(4))
    future2 = executor.submit(get_html,(2))
    future3 = executor.submit(get_html,(5))
    # print(f"future3.cancel = {future3.cancel()}" )
    # print(f" future1 {future1.done()}")
    # time.sleep(2)
    # print(f" future2 {future2.done()}")
    #
    # print(future2.result())
    print(future2.result())
    print("main")

if __name__ == '__main__':
    main()